//
//  RiskInfoHandler.js
//  SugLisSystem
//
//  Created by Mr.Right on 2013-03-25.
//  Copyright 2013 Mr.Right. All rights reserved.
//
var exeSQL = require('untils/ExeSQL');
var pubFun = require('untils/PubFun');
var dB = require('untils/DB');

/**
 * 输出需要的key&value
 * */
function CalSQLValue(sql, riskItem) {
	var tempSql = TranseToTypical(sql, riskItem);
	Ti.API.warn('[RiskInfoHandler]处理下拉选项数据库脚本;' + tempSql);
	var tempArray = exeSQL.execSQL(tempSql, exeSQL.TYPE_ARRAY);
	var tempDatas = [];
	for (var i = 0; i < tempArray.length; i++) {
		var tempData = {
			value : tempArray[i][0],
			title : tempArray[i][1]
		}
		tempDatas.push(tempData);
	}
	return tempDatas;
}

exports.CalSQLValue = CalSQLValue;

function FindTitleByValue(DataArr, value) {
	var tempTitle = '';
	for (var i = 0; i < DataArr.length; i++) {
		if (DataArr[i].value == value) {
			tempTitle = DataArr[i].title;
			break;
		}
	}
	return tempTitle;
}

exports.FindTitleByValue = FindTitleByValue;
/**
 * 替换变量
 */
function TranseToTypical(sql, riskItem) {
	var birthday = riskItem.insuSchema['birthday'];
	var appntBirthday = riskItem.appntSchema['appntbirthday'];
	var appAge = pubFun.calInterval(birthday, pubFun.getCurrentDate(), 'Y');
	var appntAge = pubFun.calInterval(birthday, pubFun.getCurrentDate(), 'Y');
	sql = sql.replace(/\?AppAge\?/g, appAge);
	sql = sql.replace(/\?Sex\?/g, riskItem.insuSchema['sex']);
	sql = sql.replace(/\?AppntAge\?/g, appntAge);
	sql = sql.replace(/\?AppntSex\?/g, riskItem.appntSchema['appntsex']);
	sql = sql.replace(/\?OccupationCode\?/g, riskItem.insuSchema['occupationcode']);
	sql = sql.replace(/\?MainPolNo\?/g, riskItem.mainPolNo);
	sql = sql.replace(/\?ContNo\?/g, riskItem.contNo);
	sql = sql.replace(/\?InsuredNo\?/g, riskItem.insuNo);
	var riksData = riskItem.riskData;
	//修正大小写问题
	var sqlArray = sql.split('?');
	var tempSQL = '';
	for (var i = 0; i < sqlArray.length; i++) {
		if (i % 2 != 0) {
			tempSQL += ('?' + sqlArray[i].toLowerCase() + '?');
		} else {
			tempSQL += sqlArray[i];
		}
	}
	if (riksData != null) {
		for (var obj in riksData) {
			eval("tempSQL = tempSQL.replace(/\\?" + obj + "\\?/g, riksData." + obj + ");");
		}
	}
	return tempSQL;
}

exports.TranseToTypical = TranseToTypical;

/**
 * 判断是否为豁免险
 * */
function isExemptionRisk(riskCode) {
	var LMRiskAppDB = new dB('LMRiskApp');
	LMRiskAppDB['riskcode'] = riskCode;
	if (LMRiskAppDB.getInfo()) {
		return LMRiskAppDB['riskprop'] == 'R';
	}
	return false;
}

exports.isExemptionRisk = isExemptionRisk; 